package com.pms.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.pms.entity.Message;
import com.pms.util.DBHelp;
import com.pms.util.RowMapper;

public class MessageDao {

	DBHelp<Message> db = new DBHelp<Message>();
	
	public void save(Message mes){
		String sql = "INSERT INTO t_message(mescontent, t_user_useid, username, createtime) VALUE(?,?,?,?)";
		db.executeSQL(sql, mes.getMescontent(), mes.getUserid(), mes.getUsername(), mes.getCreatetime());
	}
	public List<Message> findMes(){
		StringBuilder sb = new StringBuilder(); 
		sb.append("SELECT tm.mesid, tm.mescontent, tm.createtime, tm.t_user_useid, tm.`username` FROM t_message AS tm ,t_user AS tu ");
		sb.append("WHERE tm.`t_user_useid` = tu.`useid` ORDER BY createtime DESC");
		return db.executeQueryToList(sb.toString(), new MessageRowMapper());
	}
	
	private class MessageRowMapper implements RowMapper<Message>{

		@Override
		public Message mapRow(ResultSet rs) throws SQLException {

			Message mes = new Message();
			mes.setMesid(rs.getString("mesid"));
			mes.setMescontent(rs.getString("mescontent"));
			mes.setUserid(rs.getString("t_user_useid"));
			mes.setCreatetime(rs.getString("createtime"));
			mes.setUsername(rs.getString("username"));
			return mes;
		}
		
	}
}
